package com.tiger.controller;

import com.alibaba.fastjson.JSON;
import com.tiger.utils.UpdateUtils;
import com.tiger.mapper.base.ErrorMapper;
import com.tiger.mapper.base.ErrorReplyMapper;
import com.tiger.mapper.base.QuestionMapper;
import com.tiger.mapper.base.QuestionReplyMapper;
import com.tiger.pojo.base.Error;
import com.tiger.pojo.base.ErrorReply;
import com.tiger.pojo.base.Question;
import com.tiger.pojo.base.QuestionReply;
import com.tiger.pojo.myselfArticle.MyselfArticle;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;

/**
 * @author HuXuehao (StudiousTiger)
 * @desc 这个类的作用是
 * @date 2022/3/6
 */
@Slf4j
@RestController
public class MyselfArticleController {
    @Autowired
    private ErrorReplyMapper errorReplyMapper;
    @Autowired
    private QuestionReplyMapper questionReplyMapper;
    @Autowired
    private ErrorMapper errorMapper;
    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private MinioClient minioClient;
    @Value("${minio.bucketNameOfMdFile}")
    private String bucketNameOfMdFile;
    @Value("${minio.bucketNameOfMdPicture}")
    private String bucketNameOfMdPicture;

    @Autowired
    private UpdateUtils updateUtils;

    @RequestMapping(value = "/myselfArticle/info/{replyId}", name = "获取自动生成的文章/user")
    public String getArticleInfo(@PathVariable String replyId){
        String classify = getClassify(replyId);
        if ("false".equals(classify)) {
            return "false";
        }

        MyselfArticle myselfArticle = new MyselfArticle();
        try {
            if ("error".equals(classify)) {
                ErrorReply errorReply = errorReplyMapper.selectById(replyId);

                // 设置文章回复的文本
                String articleReply = getMarkdownOfTxt(errorReply.getContextAddr());
                myselfArticle.setArticleReply(articleReply);

                // 设置文章回复的标题
                Error error = errorMapper.selectById(errorReply.getErrorId());
                myselfArticle.setArticleTitle(error.getErrorTitle());

                // 设置文章标题的描述
                String tileDescribe = getMarkdownOfTxt(error.getErrorAddr());
                myselfArticle.setArticleTileDescribe(tileDescribe);

                return JSON.toJSONString(myselfArticle);
            } else {
                QuestionReply questionReply = questionReplyMapper.selectById(replyId);

                // 设置文章回复的文本
                String articleReply = getMarkdownOfTxt(questionReply.getContextAddr());
                myselfArticle.setArticleReply(articleReply);

                // 设置文章回复的标题
                Question question = questionMapper.selectById(questionReply.getQuestionId());
                myselfArticle.setArticleTitle(question.getQuestionTitle());

                // 设置文章标题的描述
                String tileDescribe = getMarkdownOfTxt(question.getQuestionAddr());
                myselfArticle.setArticleTileDescribe(tileDescribe);

                return JSON.toJSONString(myselfArticle);
            }
        } catch (Exception e) {
            log.error(e.toString());
            return "false";
        }
    }

    /**
     * 根据文件名获取 minio 服务器中对应的文件的文本
     * @param fileName 文件名
     * @return 文件对应的文本
     */
    private String getMarkdownOfTxt(String fileName) {
        try {
            // 从 minio 中获取文件流
            InputStream inputStream = minioClient.getObject(
                    GetObjectArgs.builder()
                            .bucket(bucketNameOfMdFile)
                            .object(fileName)
                            .build());

            // 将 InputStream 转换为 String
            String res = new BufferedReader(new InputStreamReader(inputStream))
                    .lines().collect(Collectors.joining(System.lineSeparator()));

            return updateUtils.updateMDOfImgURL(res, bucketNameOfMdPicture);

        } catch (Exception e) {
            log.error(e.toString());
            return "false";
        }
    }

    /**
     * 根据回复的ID，判断是回复 error 的，还是回复 question
     * @param replyId
     * @return
     */
    private String getClassify(String replyId) {
        try {
            ErrorReply errorReply = errorReplyMapper.selectById(replyId);
            if (errorReply == null) {
                return "question";
            } else {
                return "error";
            }
        } catch (Exception e) {
            log.error(e.toString());
            return "false";
        }
    }
}
